package com.pj.wisdomlogistics.ui.activity;
import android.content.ContentValues;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import com.pj.wisdomlogistics.MyApplication;
import com.pj.wisdomlogistics.R;
import com.pj.wisdomlogistics.cons.Cons;
import com.pj.wisdomlogistics.entity.DBLoginInfoObj;
import com.pj.wisdomlogistics.entity.User;
import com.pj.wisdomlogistics.mvp.contract.LoginContract;
import com.pj.wisdomlogistics.mvp.frame.MvpActivity;
import com.pj.wisdomlogistics.mvp.frame.base.BaseView;
import com.pj.wisdomlogistics.mvp.presenter.LoginPresenter;
import com.pj.wisdomlogistics.other.EventCenter;
import com.pj.wisdomlogistics.ui.adapter.UserHisAdapter;
import com.pj.wisdomlogistics.utils.ActivityManagerUtil;
import com.pj.wisdomlogistics.utils.CustomToast;
import com.pj.wisdomlogistics.utils.DBHelper;
import com.pj.wisdomlogistics.utils.LoginInfoHandler;
import com.pj.wisdomlogistics.utils.SPUtils;
import java.util.ArrayList;
import java.util.List;
import br.com.simplepass.loading_button_lib.customViews.CircularProgressButton;
import br.com.simplepass.loading_button_lib.interfaces.OnAnimationEndListener;
import butterknife.BindView;
import butterknife.OnClick;


public class LoginActivity extends MvpActivity<LoginPresenter> implements LoginContract.View, UserHisAdapter.itemClick {
    @BindView(R.id.et_username)
    EditText mEtUsername;
    @BindView(R.id.et_password)
    EditText mEtPassword;
    @BindView(R.id.bt_login)
    CircularProgressButton mBtLogin;
    @BindView(R.id.rl_other)
    RelativeLayout mRlOther;
    @BindView(R.id.ll_username)
    LinearLayout mLlUsername;
    @BindView(R.id.iv_choose_account)
    ImageView mIvPull;

    private String currentUserName;
    private String currentPwd;

    private PopupWindow mPopupWindow;
    private boolean init_flag = false;// 浮动窗口显示标示符
    private UserHisAdapter mAdapter;

    private long mExitTime = 0;


    private List<DBLoginInfoObj> infoObjs;// 保存登陆信息数据对象
    private static final String TBL_LOGIN_INFO = "LoginInfo";// 用户登陆信息
    private Handler mHandler = new Handler() {// 处理消息更新UI
        @Override
        public void handleMessage(Message msg) {
            DBHelper dbHelper = new DBHelper(LoginActivity.this);
            switch (msg.what) {
                case 1:// 根据返回的id，将数据显示在输入框中
                    int sel_id = (int) msg.obj;
                    int _id = infoObjs.get(sel_id).getID();
                    String UserName = infoObjs.get(sel_id).getUsername();
                    String PassWord = infoObjs.get(sel_id).getPassword();
                    // 先删除再插入
                    dbHelper.del(_id, TBL_LOGIN_INFO);
                    mEtUsername.setText(UserName);
                    mEtPassword.setText(PassWord);
                    currentUserName = UserName;
                    currentPwd = PassWord;
                    mPopupWindow.dismiss();
                    mRlOther.setVisibility(View.VISIBLE);
                    mIvPull.setImageResource(R.drawable.pull);

                    mBtLogin.startAnimation();
                    mPresenter.login(UserName, PassWord);
                    break;
                case 2:// 根据返回的ID，删除数据
                    int del_id = (int) msg.obj;
                    int id = infoObjs.get(del_id).getID();
                    dbHelper.del(id, TBL_LOGIN_INFO);
                    mAdapter.removeItem(del_id);

                    if (mAdapter.getItemCount() == 0) {
                        mPopupWindow.dismiss();
                        mRlOther.setVisibility(View.VISIBLE);
                        mIvPull.setImageResource(R.drawable.pull);
                    }

                    break;
            }
        }
    };

    @Override
    public void initView() {
        ultimateBar.setImmersionBar();
        initPopuWindow();
        infoObjs = new ArrayList<>();
    }

    private void initPopuWindow() {

        // 浮动窗口的布局
        final View userView = this.getLayoutInflater().inflate(
                R.layout.layout_userview, null);
        RecyclerView mRvUser = (RecyclerView) userView.findViewById(R.id.rv_user);
        // 初始化适配器
        mAdapter = new UserHisAdapter(this);
        mRvUser.setLayoutManager(new LinearLayoutManager(this));
        mRvUser.setAdapter(mAdapter);

        ViewTreeObserver vto = mLlUsername.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mLlUsername.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                int width = mLlUsername.getWidth();

                // 定义一个浮动窗口，并设置
                mPopupWindow = new PopupWindow(userView, width,
                        LinearLayout.LayoutParams.WRAP_CONTENT, true);
                mPopupWindow.setOutsideTouchable(false);
                mPopupWindow.setFocusable(false);
                mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
            }
        });

        mAdapter.setListener(this);

    }

    @Override
    public void initData() {

    }

    @Override
    public int getContentView() {
        return R.layout.activity_login;
    }

    @Override
    public boolean isApplyEventBus() {
        return true;
    }

    @Override
    public boolean isApplyButterKnife() {
        return true;
    }

    @Override
    public void onEventCome(EventCenter eventCenter) {
        if(eventCenter.getEventCode() == Cons.Other.REGIST){
            String[] user = ((String) eventCenter.getData()).split(",");
            mEtUsername.setText(user[0]);
            mEtPassword.setText(user[1]);
            mPresenter.login(user[0] , user[1]);
        }
    }

    @Override
    protected BaseView getBaseView() {
        return this;
    }

    @Override
    public void showError(final String errorMsg) {
        mBtLogin.revertAnimation(new OnAnimationEndListener() {
            @Override
            public void onAnimationEnd() {
                mBtLogin.setText("失败请重试");
            }
        });
        CustomToast.showToast(this, errorMsg, 1000);
    }

    @Override
    public void showLoginSuccess(User user) {
        SPUtils.saveUser(user);
        MyApplication.loadUser();
        CustomToast.showToast(this, "登陆成功", 1000);
        startActivity(MainActivity.class);
        ActivityManagerUtil.create().finishActivity();


        // 登录成功将数据保存到SQLite中
        ContentValues values = new ContentValues();
        values.put("UserName", currentUserName);
        values.put("PassWord", currentPwd);
        DBHelper dbHelper = new DBHelper(this);

        // 标示符是否要插入
        boolean flag = false;
        // 判断密码是否变更
        boolean flag_pwd = false;
        int id = -1;
        // 判断当前用户名是否在数据库存在
        LoginInfoHandler mHandler = LoginInfoHandler
                .create(this);
        List<DBLoginInfoObj> info = mHandler.getLoginInfoObj();
        for (int i = 0; i < info.size(); i++) {
            if (info.get(i).getUsername().equals(user.getLogin_name())) {
                flag = true;
                if (!info.get(i).getPassword().equals(user.getPassword())) {
                    flag_pwd = true;
                    id = info.get(i).getID();
                }
            }
        }
        if (!flag) {
            dbHelper.insert(values, TBL_LOGIN_INFO);
        }
        if (flag && flag_pwd) {
            dbHelper.del(id, TBL_LOGIN_INFO);
            dbHelper.insert(values, TBL_LOGIN_INFO);
        }

    }

    @OnClick({R.id.tv_register, R.id.tv_forget_pwd, R.id.tv_protocol, R.id.bt_login, R.id.iv_choose_account})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_register:
                startActivity(RegisterActivity.class);
                break;
            case R.id.tv_forget_pwd:
                break;
            case R.id.tv_protocol:
                break;
            case R.id.bt_login:
                String username = mEtUsername.getText().toString().trim();
                String password = mEtPassword.getText().toString().trim();
                if (TextUtils.isEmpty(username)) {
                    CustomToast.showToast(this, "账号不能为空", 1000);
                    return;
                }


                if (TextUtils.isEmpty(password)) {
                    CustomToast.showToast(this, "密码不能为空", 1000);
                    return;
                }

                currentUserName = username;
                currentPwd = password;

                mBtLogin.startAnimation();
                mPresenter.login(username, password);

                break;
            case R.id.iv_choose_account:
                init_flag = !init_flag;

                if (init_flag) {
                    mRlOther.setVisibility(View.GONE);
                    mIvPull.setImageResource(R.drawable.withdraw);
                    mPopupWindow.showAsDropDown(mLlUsername);

                    infoObjs = LoginInfoHandler.create(this).getLoginInfoObj();
                    mAdapter.setList(infoObjs);
                } else {
                    mRlOther.setVisibility(View.VISIBLE);
                    mIvPull.setImageResource(R.drawable.pull);
                    mPopupWindow.dismiss();
                }

                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mBtLogin.dispose();
    }

    @Override
    public void deleteClick(int id) {
        Message msg = new Message();
        msg.what = 2;
        msg.obj = id;
        mHandler.sendMessage(msg);
    }

    @Override
    public void chooseClick(int id) {
        Message msg = new Message();
        msg.what = 1;
        msg.obj = id;
        mHandler.sendMessage(msg);
    }

    @Override
    public void onBackPressed() {
        if (mPopupWindow.isShowing()) {
            init_flag = !init_flag;
            mRlOther.setVisibility(View.VISIBLE);
            mIvPull.setImageResource(R.drawable.pull);
            mPopupWindow.dismiss();
        } else {
            if (System.currentTimeMillis() - mExitTime > 2000) {
                CustomToast.showToast(this, "再按一次退出程序", 1000);
                mExitTime = System.currentTimeMillis();
            }else{
                finish();
            }
        }
    }

}
